package com.yl.framework.interceptor;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yl.common.config.jianke.JianKeProperties;
import com.yl.common.core.domain.Result;
import com.yl.common.core.domain.entity.SysUser;
import com.yl.common.enums.ErrorCode;
import com.yl.common.utils.SecurityUtils;
import com.yl.common.utils.StringUtils;
import com.yl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import java.util.Objects;

/**
 * 建科请求拦截器
 */
@Slf4j
@Component
public class JianKeInterceptor implements HandlerInterceptor {
    //请求头参数key
    @Value("${token.header}")
    private String header;

    @Autowired
    private JianKeProperties jianKeProperties;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 请求开始执行
     * 处理自定义的验证逻辑
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //数据解密
        String userName = "";
        //从request Headers 获取token参数 建科给的token示例 VGPRrfdxVYISu0fb3BH0dFNnrxBPtk1ooVe3yCy3KkI=
        String token = request.getHeader(header);
        if(StringUtils.isEmpty(token)) {
            token = request.getParameter("token");
        }
        //解密获取用户账号 建科数据解密后 格式如 admin@2024-12-12 00:00:00 账号就是admin
        String userStr = SecurityUtils.decryptAES(token, jianKeProperties.getKey());
        if(StrUtil.isBlank(userStr)||!userStr.contains("@")){
            write(response, ErrorCode.ERROR_10000.getCode(),ErrorCode.ERROR_10000.getDescribe());
            return false;
        }

        String[] split = userStr.split("@");
        userName = split[0];
        if(StrUtil.isBlank(userName)){
            write(response,ErrorCode.ERROR_10001.getCode(),ErrorCode.ERROR_10001.getDescribe());
            return false;
        }

        //通过账号查询用户数据 存入ThreadLocal中
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUser::getUserName,userName);
        SysUser sysUser = sysUserService.getOne(lqw);
        if(Objects.isNull(sysUser)){
            write(response,ErrorCode.ERROR_10002.getCode(),ErrorCode.ERROR_10002.getDescribe());
            return false;
        }
        sysUser.setJianKeToken(token);
        UserContext.setUser(sysUser);

        return true;
    }


    /**
     * 像response中写入
     */
    public void write(HttpServletResponse response,Integer code,String msg) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(JSONUtil.toJsonStr(Result.fail(code,msg)));
        pw.flush();
        pw.close();
    }

    /**
     * 请求结束执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        //清空Treadlocal避免内存泄露
        UserContext.removeUser();
        //log.info("请求结束执行");
    }



}
